<template>
  <div class="min-h-screen p-4">
    <div class="max-w-4xl mx-auto">
      <!-- 顶部导航 -->
      <div class="flex justify-between items-center mb-8">
        <button @click="$emit('back')"
          class="px-4 py-2 bg-gray-500 text-white rounded hover:bg-gray-600 flex items-center gap-2">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18" />
          </svg>
          返回
        </button>
        <h1 class="text-3xl font-bold text-center">预设图案</h1>
        <div class="w-24"></div>
      </div>

      <!-- 图案分类选择 -->
      <div class="mb-6">
        <div class="flex gap-2 overflow-x-auto pb-2">
          <button v-for="category in categories" :key="category" 
            @click="selectedCategory = category" 
            :class="[
              'px-4 py-2 rounded whitespace-nowrap',
              selectedCategory === category
                ? 'bg-blue-500 text-white'
                : 'bg-gray-200 text-gray-700 hover:bg-gray-300'
            ]"
          >
            {{ getCategoryName(category) }}
          </button>
        </div>
      </div>

      <!-- 图案列表 -->
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        <div v-for="pattern in filteredPatterns" :key="pattern.id"
          class="bg-white rounded-lg shadow-md p-4 hover:shadow-lg transition-shadow">
          <h3 class="text-lg font-semibold mb-2">{{ pattern.name }}</h3>
          <p class="text-gray-600 text-sm mb-4">{{ pattern.description }}</p>

          <!-- 图案预览 -->
          <div class="mb-4">
            <div class="grid gap-1" :style="{
              gridTemplateColumns: `repeat(${pattern.pattern[0].length}, 1fr)`
            }">
              <div v-for="(row, y) in pattern.pattern" :key="y" class="flex">
                <div v-for="(cell, x) in row" :key="x" class="aspect-square border border-gray-200"
                  :class="cell ? 'bg-blue-500' : 'bg-white'"></div>
              </div>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="flex justify-end gap-2">
            <button @click="handlePreviewPattern(pattern)"
              class="px-3 py-1 bg-gray-200 text-gray-700 rounded hover:bg-gray-300">
              预览
            </button>
            <button @click="handleApplyPattern(pattern)" class="px-3 py-1 bg-green-500 text-white rounded hover:bg-green-600">
              应用
            </button>
          </div>
        </div>
      </div>

      <!-- 预览模态框 -->
      <div v-if="previewPattern" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4">
        <div class="bg-white rounded-lg p-6 max-w-2xl w-full">
          <div class="flex justify-between items-center mb-4">
            <h2 class="text-xl font-bold">{{ previewPattern.name }}</h2>
            <button @click="closePreview" class="text-gray-500 hover:text-gray-700">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>
          
          <!-- 预览画布 -->
          <div class="mb-4">
            <canvas ref="previewCanvas" class="w-full border rounded"></canvas>
          </div>

          <!-- 预览控制 -->
          <div class="flex justify-between items-center">
            <div class="flex gap-2">
              <button @click="togglePreview" class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600">
                {{ isPreviewRunning ? '暂停' : '开始' }}
              </button>
              <button @click="handleApplyPattern(previewPattern)" class="px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600">
                应用
              </button>
            </div>
            <div class="flex items-center gap-2">
              <label>速度:</label>
              <input type="range" v-model="previewSpeed" min="100" max="1000" step="100" class="w-32">
              <span>{{ previewSpeed }}ms</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onUnmounted, nextTick } from 'vue'
import { patterns, getPatternsByCategory } from '../patterns'
import { GameOfLife } from '../game'
import { setCurrentPattern } from '../store/patternStore'

const emit = defineEmits(['back', 'preview', 'apply', 'gotoGame'])

// 图案分类
const categories = Object.keys(patterns)
const selectedCategory = ref(categories[0])

// 预览相关
const previewCanvas = ref(null)
const previewPattern = ref(null)
const previewGame = ref(null)
const isPreviewRunning = ref(false)
const previewSpeed = ref(500)
let previewAnimationFrame = null
let lastPreviewDrawTime = 0
const PREVIEW_DRAW_INTERVAL = 16 // 约60fps

// 获取分类名称
const getCategoryName = (category) => {
  const names = {
    stillLife: '静物',
    oscillators: '振荡器',
    gliders: '滑翔机'
  }
  return names[category] || category
}

// 获取当前分类的图案
const filteredPatterns = computed(() => {
  return getPatternsByCategory(selectedCategory.value)
})

// 预览图案
const handlePreviewPattern = (pattern) => {
  previewPattern.value = pattern
  openPreview(pattern)
}

// 打开预览
const openPreview = (pattern) => {
  previewPattern.value = pattern
  isPreviewRunning.value = false

  // 初始化预览游戏
  nextTick(async () => {
    const canvas = previewCanvas.value
    const container = canvas.parentElement
    const size = Math.min(container.clientWidth - 32, 400) // 限制最大尺寸
    // 使用整数像素值
    canvas.width = Math.floor(size)
    canvas.height = Math.floor(size)

    // 创建预览游戏实例
    const gridSize = 20 // 固定预览大小
    previewGame.value = new GameOfLife(gridSize, gridSize)

    // 放置图案
    const patternHeight = pattern.pattern.length
    const patternWidth = pattern.pattern[0].length
    const startX = Math.floor((gridSize - patternWidth) / 2)
    const startY = Math.floor((gridSize - patternHeight) / 2)

    // 清空网格
    for (let y = 0; y < gridSize; y++) {
      for (let x = 0; x < gridSize; x++) {
        previewGame.value.grid[y][x] = false
      }
    }

    // 放置图案
    for (let y = 0; y < patternHeight; y++) {
      for (let x = 0; x < patternWidth; x++) {
        const gridX = startX + x
        const gridY = startY + y
        if (gridX >= 0 && gridX < gridSize && gridY >= 0 && gridY < gridSize) {
          previewGame.value.grid[gridY][gridX] = pattern.pattern[y][x] === 1
        }
      }
    }

    drawPreview()
  })
}

// 关闭预览
const closePreview = () => {
  previewPattern.value = null
  isPreviewRunning.value = false
  clearTimeout(previewAnimationFrame)
}

// 预览动画循环
const previewLoop = () => {
  if (!isPreviewRunning.value) return

  const now = Date.now()
  if (now - lastPreviewDrawTime < PREVIEW_DRAW_INTERVAL) {
    previewAnimationFrame = setTimeout(() => {
      previewLoop()
    }, previewSpeed.value)
    return
  }
  lastPreviewDrawTime = now

  previewGame.value.nextGeneration()
  drawPreview()

  previewAnimationFrame = setTimeout(() => {
    previewLoop()
  }, previewSpeed.value)
}

// 切换预览运行状态
const togglePreview = () => {
  isPreviewRunning.value = !isPreviewRunning.value
  if (isPreviewRunning.value) {
    previewLoop()
  } else {
    clearTimeout(previewAnimationFrame)
  }
}

// 绘制预览
const drawPreview = () => {
  if (!previewGame.value || !previewCanvas.value) return

  const canvas = previewCanvas.value
  const ctx = canvas.getContext('2d')
  const gridSize = previewGame.value.width
  const cellSize = Math.floor(canvas.width / gridSize)

  // 使用整数像素值避免模糊
  const width = Math.floor(canvas.width)
  const height = Math.floor(canvas.height)

  ctx.clearRect(0, 0, width, height)

  // 绘制网格线
  ctx.strokeStyle = '#ddd'
  ctx.lineWidth = 0.5

  for (let i = 0; i <= gridSize; i++) {
    const pos = Math.floor(i * cellSize)
    ctx.beginPath()
    ctx.moveTo(pos, 0)
    ctx.lineTo(pos, height)
    ctx.stroke()

    ctx.beginPath()
    ctx.moveTo(0, pos)
    ctx.lineTo(width, pos)
    ctx.stroke()
  }

  // 绘制细胞
  ctx.fillStyle = '#000'
  for (let y = 0; y < gridSize; y++) {
    for (let x = 0; x < gridSize; x++) {
      if (previewGame.value.grid[y][x]) {
        const cellX = Math.floor(x * cellSize)
        const cellY = Math.floor(y * cellSize)
        const cellWidth = Math.ceil(cellSize) - 1
        const cellHeight = Math.ceil(cellSize) - 1
        ctx.fillRect(cellX, cellY, cellWidth, cellHeight)
      }
    }
  }
}

// 应用图案
const handleApplyPattern = (pattern) => {
  // 如果传入了pattern参数，直接使用它
  const targetPattern = pattern || previewPattern.value
  if (!targetPattern) {
    console.log('Patterns.vue: 没有可应用的图案')
    return
  }
  
  // 设置当前图案
  setCurrentPattern(targetPattern)
  console.log('Patterns.vue: 已设置当前图案', {
    patternName: targetPattern.name,
    patternCategory: targetPattern.category
  })
  
  // 关闭预览
  closePreview()
  console.log('Patterns.vue: 已关闭预览')
  
  // 直接跳转到游戏页面
  console.log('Patterns.vue: 准备跳转到游戏页面')
  emit('gotoGame')
  console.log('Patterns.vue: 已触发gotoGame事件')
}

// 组件卸载时清理
onUnmounted(() => {
  clearTimeout(previewAnimationFrame)
})
</script>